package com.example.redisdemo.apiIdempotent.service.Impl;

import com.example.redisdemo.accessLimit.exception.ServiceException;
import com.example.redisdemo.accessLimit.util.Constant;
import com.example.redisdemo.apiIdempotent.service.TokenService;
import com.example.redisdemo.util.HttpResult;
import com.example.redisdemo.util.HttpStatus;
import com.example.redisdemo.util.RandomUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.text.StrBuilder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @Description
 * @ClassName TokenServiceImpl
 * @Author jiang_11445266119198
 * @Date 2022/7/19 12:47
 */
@Service
public class TokenServiceImpl implements TokenService {

    private static final String TOKEN_NAME = "token";
    @Resource
    private StringRedisTemplate stringTemplate;

    @Override
    public HttpResult createToken() {
        String str = RandomUtil.UUID32();
        //StrBuilder token = new StrBuilder();
        StringBuffer token = new StringBuffer();
        token.append(Constant.Redis.TOKEN_PREFIX).append(str);
        //ValueOperations<String, String> valueTemplate = stringTemplate.opsForValue();
        stringTemplate.opsForValue().set(token.toString(), token.toString(), Constant.Redis.EXPIRE_TIME_MINUTE);

        return HttpResult.newSuccess(token.toString());
    }

    @Override
    public void checkToken(HttpServletRequest request) {
        String token = request.getHeader(TOKEN_NAME);
        if (StringUtils.isBlank(token)) {// header中不存在token
            token = request.getParameter(TOKEN_NAME);
            if (StringUtils.isBlank(token)) {// parameter中也不存在token
                throw new ServiceException(HttpStatus.ILLEGAL_ARGUMENT.getMsg());
            }
        }
        ValueOperations<String, String> valueTemplate = stringTemplate.opsForValue();
        if (!stringTemplate.hasKey(token)) {
            throw new ServiceException(HttpStatus.REPETITIVE_OPERATION.getMsg());
        }

        Boolean delete = stringTemplate.delete(token);
        //Long del = stringTemplate.delete(token);
        if (!delete) {
            throw new ServiceException(HttpStatus.REPETITIVE_OPERATION.getMsg());
        }
    }
}
